package com.demo.aspect;

import com.demo.annotations.Trans;
import com.demo.utils.TransactionMnanager;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * 开发切面，实现环绕通知 根据目标方法是否有@Trans决定要不要增强事务控制
 */
@Component
@Aspect
public class TransAspect {

    @Around("execution(* com.demo.service..*(..))&&@annotation(ta)")
    public Object aroundTrans(ProceedingJoinPoint pjp, Trans ta) throws Throwable {
        try {
            TransactionMnanager.startTran();//开启事务
            Object proceed = pjp.proceed();//执行目标方法
            TransactionMnanager.commitTran();//提交事务
            return proceed;
        } catch (Throwable throwable) {
            TransactionMnanager.rollbackTran();//回滚事务
            throw throwable;
        }finally {
            TransactionMnanager.release();//释放资源
        }
    }
}

